package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"net"
	"time"
)

const (
	SERVER_NETWORK = "tcp"
	SERVER_ADDRESS = "127.0.0.1:8085"
	DELIMITER      = '\t'
)

func printLog(format string, args ...interface{}) {
	fmt.Printf("%s", fmt.Sprintf(format, args...))
}

var sendMsg string = "hello"

func main() {

	conn, err := net.DialTimeout(SERVER_NETWORK, SERVER_ADDRESS, 2*time.Second)
	if err != nil {
		printLog("Dial err :%s\n", err)
		return
	}
	defer conn.Close()
	printLog("Conected to server.(remote address :%s,local address :%s)\n", conn.RemoteAddr(), conn.LocalAddr())
	time.Sleep(200 * time.Millisecond)
	var writeBuf bytes.Buffer
	for i := 0; i < 10; i++ {
		writeBuf.WriteString(sendMsg)
		writeBuf.WriteByte(DELIMITER)
	}

	n, err := conn.Write(writeBuf.Bytes())
	if err != nil {
		printLog("Write err :%s(Client)\n", err)
	}
	printLog("Send messge (wirtten %d bytes)\n", n)

	//send io.EOF
	writeBuf.WriteString(io.EOF.Error())
	writeBuf.WriteByte(DELIMITER)
	n, err = conn.Write(writeBuf.Bytes())
	if err != nil {
		printLog("Write err :%s(Client)\n", err)
	}
	printLog("Send messge (wirtten %d bytes)\n", n)

	reader := bufio.NewReader(conn)
	for {
		readBytes, err := reader.ReadBytes(DELIMITER)

		if err != nil {
			printLog("read from Server err :%s\n", err)
			return
		}
		if string(readBytes[:len(readBytes)-1]) == "The message from server :EOF" {
			break
		}
		printLog("Received response :%s(Client)\n", string(readBytes[:len(readBytes)-1]))
	}
}
